package com.bicon.botu.mall.goods.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.mall.goods.commons.ExcelData;
import com.bicon.botu.mall.goods.commons.ExportExcelUtils;
import com.bicon.botu.mall.goods.commons.GoodsConstants;
import com.bicon.botu.mall.goods.entity.ProductComment;
import com.bicon.botu.mall.goods.service.IProductCommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * <p> 商品评论API-管理端
 * </p>
 *
 * @author liushujie
 * @since 2018/5/29.
 */
@RestController
@RequestMapping("/V3.0.0/product-comment")
public class ProductCommentController extends BaseController {


    //SY0013-05-评价信息列表导出—管理端

    @Autowired
    IProductCommentService iProductCommentService;

    /**
     * SY0013-02-评价列表查询—管理端
     * SY0013-06-评价信息列表统计—管理端
     * SY0013-13-评论排序—管理端
     *
     * @param pageNo      当前页
     * @param pageSize    页码
     * @param replyStatus 处理状态 未处理 1 ; 已处理评论 2
     * @param productName 商品名称
     * @param createDate  评论时间
     * @param productType 商品类型
     * @param level       评价级别 【好评，2中评，3差评】
     * @param isPictures  是否有图【0有，1没有】
     * @param isAsc       是否升序，默认降序false
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public BaseResult search(@RequestParam(value = "pageNo") int pageNo, @RequestParam(value = "pageSize") int pageSize,
                             @RequestParam(value = "replyStatus", defaultValue = "0") Integer replyStatus, @RequestParam(value = "productName", required = false) String productName,
                             @RequestParam(value = "productType", required = false) String productType,
                             @RequestParam(value = "createDate", required = false) String createDate,
                             @RequestParam(value = "level", required = false) Integer level,
                             @RequestParam(value = "isPictures", required = false) Integer isPictures,
                             @RequestParam(value = "orderBy", required = false) String orderBy,
                             @RequestParam(value = "isAsc", required = false, defaultValue = "0") Integer isAsc) {

        boolean asc = false;
        if(isAsc == 1){
            asc = true;
        }
        Map<String, Object> mapAll = new HashMap<>(5);
        //评论总数
        int total = iProductCommentService.selectCount(new EntityWrapper<ProductComment>().eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        //未处理 1
        int level1 = iProductCommentService.selectCount(new EntityWrapper<ProductComment>().eq("reply_status", 1).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        //已处理评论 2
        int level2 = iProductCommentService.selectCount(new EntityWrapper<ProductComment>().eq("reply_status", 2).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        //拼装查询参数
        EntityWrapper<ProductComment> entityWrapper = new EntityWrapper<ProductComment>();
        if (!StringUtils.isEmpty(productName)) {
            entityWrapper.like(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_PRODUCT_NAME, productName);
        }
        if (!StringUtils.isEmpty(createDate)) {
            entityWrapper.like(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_CREATE_DATE, createDate);
        }
        if (!StringUtils.isEmpty(productType)) {
            entityWrapper.eq(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_PRODUCT_TYPE, productType);
        }
        if (null != level) {
            entityWrapper.eq(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_LEVEL, level);
        }
        if (null != isPictures) {
            entityWrapper.eq(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_IS_PICTURES, isPictures);
        }
        //默认条件  根据回复时间降序
        entityWrapper.eq(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_LOGIC_DELETE, Constants.DEL_LOGIC_NORMAL);
        if (StringUtils.isEmpty(orderBy)) {
            entityWrapper.orderBy(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_CREATE_DATE, asc);
        } else if (StringUtils.equalsIgnoreCase(orderBy, "replyStatus")) {
            entityWrapper.orderBy(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_REPLY_STATUS, asc);
        } else if (StringUtils.equalsIgnoreCase(orderBy, "productType")) {
            entityWrapper.orderBy(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_PRODUCT_TYPE, asc);
        } else if (StringUtils.equalsIgnoreCase(orderBy, "level")) {
            entityWrapper.orderBy(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_LEVEL, asc);
        } else if (StringUtils.equalsIgnoreCase(orderBy, "isPictures")) {
            entityWrapper.orderBy(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_IS_PICTURES, asc);
        }else{
            entityWrapper.orderBy(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_CREATE_DATE, asc);
        }
        if (replyStatus.equals(GoodsConstants.BOTU_PRODUCT_COMMENT_REPLYSTATUS)) {
            //查已处理 2 的条件
            Page<ProductComment> page = new ProductComment().selectPage(new Page<>(pageNo, pageSize), entityWrapper.eq("reply_status", 2));
            mapAll.put("page", page);
        } else if (replyStatus.equals(GoodsConstants.BOTU_PRODUCT_COMMENT_UN_REPLYSTATUS)) {
            //查未处理 1 的条件
            Page<ProductComment> page = new ProductComment().selectPage(new Page<>(pageNo, pageSize), entityWrapper.eq("reply_status", 1));
            mapAll.put("page", page);
        } else {
            //默认只根据条件查
            Page<ProductComment> page = new ProductComment().selectPage(new Page<>(pageNo, pageSize), entityWrapper);
            mapAll.put("page", page);
        }
        mapAll.put("total", total);
        mapAll.put("level1", level1);
        mapAll.put("level2", level2);
        return sendResult200(mapAll);
    }


    /**
     * SY0013-03订单评价详细信息查询—管理端
     *
     * @param id 评论id
     * @return 评论对象
     */
    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public BaseResult details(@RequestParam(value = "id") String id) {
        ProductComment productComment = new ProductComment().selectById(id);
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, productComment);
    }


    /**
     * SY0013-04-评价信息批量隐藏/展示查询—管理端
     *
     * @param ids     ids
     * @param display 显示状态 0：是，1：否
     * @return
     */
    @RequestMapping(value = "/display", method = RequestMethod.POST)
    public BaseResult displayComment(@RequestParam("ids") String ids, @RequestParam("display") Integer display) {
        String[] idArray = ids.split(",");
        List<ProductComment> productCommentList = new ArrayList<>();
        for (int i = 0; i < idArray.length; i++) {
            ProductComment productComment = new ProductComment();
            productComment.setId(idArray[i]);
            productComment.setDisplay(display);
            productComment.preUpdate();
            productCommentList.add(productComment);
        }
        boolean result = iProductCommentService.updateBatchById(productCommentList);
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }


    /**
     * SY0013-09-评价信息客服回复—管理端
     *
     * @param id           评论id
     * @param replyContent 评论内容
     * @return
     */
    @RequestMapping(value = "/reply", method = RequestMethod.POST)
    public BaseResult replyComment(@RequestParam("id") String id, @RequestParam("replyContent") String replyContent) {
        ProductComment productComment = new ProductComment();
        productComment.setId(id);
        productComment.setReplyContent(replyContent);
        productComment.setReplyStatus(GoodsConstants.BOTU_PRODUCT_COMMENT_REPLYSTATUS);
        boolean result = iProductCommentService.updateById(productComment);
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }


    /**
     * SY0013-05-评价信息列表导出—管理端
     *
     * @param response    response
     * @param replyStatus 处理状态
     * @param productName 商品名称
     * @param productType 产品类型
     * @param createDate  评论时间
     * @param level       评论级别
     * @param isPictures  是否有图
     * @param orderBy     排序字段
     * @param isAsc       是否升序
     * @throws Exception
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(HttpServletResponse response, @RequestParam(value = "replyStatus", defaultValue = "0") Integer replyStatus, @RequestParam(value = "productName", required = false) String productName,
                       @RequestParam(value = "productType", required = false) String productType,
                       @RequestParam(value = "createDate", required = false) String createDate,
                       @RequestParam(value = "level", required = false) Integer level,
                       @RequestParam(value = "isPictures", required = false) Integer isPictures,
                       @RequestParam(value = "orderBy", required = false) String orderBy,
                       @RequestParam(value = "isAsc", required = false, defaultValue = "0") Integer isAsc) throws Exception {
        boolean asc = false;
        if(isAsc == 1){
            asc = true;
        }
        EntityWrapper<ProductComment> entityWrapper = new EntityWrapper<ProductComment>();
        if (!StringUtils.isEmpty(productName)) {
            entityWrapper.like("product_name", productName);
        }
        if (!StringUtils.isEmpty(createDate)) {
            entityWrapper.like("create_date", createDate);
        }
        if (!StringUtils.isEmpty(productType)) {
            entityWrapper.eq("product_type", productType);
        }
        if (null != level) {
            entityWrapper.eq("level", level);
        }
        if (null != isPictures) {
            entityWrapper.eq("is_pictures", isPictures);
        }
        //默认条件  根据回复时间降序
        entityWrapper.eq("logic_delete", Constants.DEL_LOGIC_NORMAL);
        if (StringUtils.isEmpty(orderBy)) {
            entityWrapper.orderBy("create_date", asc);
        } else if (StringUtils.equalsIgnoreCase(orderBy, "replyStatus")) {
            entityWrapper.orderBy("reply_status", asc);
        } else if (StringUtils.equalsIgnoreCase(orderBy, "productType")) {
            entityWrapper.orderBy("product_type", asc);
        } else if (StringUtils.equalsIgnoreCase(orderBy, "level")) {
            entityWrapper.orderBy("level", asc);
        } else if (StringUtils.equalsIgnoreCase(orderBy, "isPictures")) {
            entityWrapper.orderBy("is_pictures", asc);
        }else{
            entityWrapper.orderBy(GoodsConstants.BOTU_PRODUCT_COMMENT_ORDER_BY_CREATE_DATE, asc);
        }
        List<ProductComment> productCommentList = new ArrayList<>();
        if (replyStatus.equals(GoodsConstants.BOTU_PRODUCT_COMMENT_REPLYSTATUS)) {
            //查已处理 2 的条件
            productCommentList = iProductCommentService.selectList(entityWrapper.eq("reply_status", 2));
        } else if (replyStatus.equals(GoodsConstants.BOTU_PRODUCT_COMMENT_UN_REPLYSTATUS)) {
            //查未处理 1 的条件
            productCommentList = iProductCommentService.selectList(entityWrapper.eq("reply_status", 1));
        } else {
            //默认只根据条件查
            productCommentList = iProductCommentService.selectList(entityWrapper);
        }
        ExcelData data = new ExcelData();
        data.setName("评论列表");
        List<String> titles = new ArrayList();
        titles.add("评论ID");
        titles.add("订单编号");
        titles.add("评论状态");
        titles.add("商品类型");
        titles.add("商品名称");
        titles.add("评价内容");
        titles.add("评价等级");
        titles.add("是否有图");
        titles.add("评价时间");
        titles.add("客服评价");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for (int i = 0; i < productCommentList.size(); i++) {
            List<Object> row = new ArrayList();
            row.add(productCommentList.get(i).getId());
            row.add(productCommentList.get(i).getOrderNo());
            row.add(productCommentList.get(i).getReplyStatus() == 1 ? "未处理" : "已处理");
            row.add("1".equalsIgnoreCase(productCommentList.get(i).getProductType()) ? "普通商品" : "定制商品");
            row.add(productCommentList.get(i).getProductName() + productCommentList.get(i).getSkuName());
            row.add(productCommentList.get(i).getContent());
            switch (productCommentList.get(i).getLevel()) {
                case 1:
                    row.add("好评");
                    break;
                case 2:
                    row.add("中评");
                    break;
                default:
                    row.add("差评");
                    break;

            }
            row.add(productCommentList.get(i).getIsPictures() == 0 ? "有" : "没有");
            row.add(dateToStr(productCommentList.get(i).getCreateDate()));
            row.add(productCommentList.get(i).getReplyContent() == null ? "" : productCommentList.get(i).getReplyContent());
            rows.add(row);
        }
        data.setRows(rows);
        String fileName = "评论-" + System.currentTimeMillis() + ".xlsx";
        ExportExcelUtils.exportExcel(response, fileName, data);
    }

    /**
     * 日期转换 date转String
     *
     * @param date
     * @return
     */
    private String dateToStr(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        return dateString;
    }


}
